//
//  NSArray+MCError.m
//  MCOCModule
//
//  Created by mingci on 2021/10/14.
//

#import "NSArray+MCError.h"
#import <objc/runtime.h>


/*
  在iOS中NSNumber、NSArray、NSDictionary等这些类都是类簇，一个NSArray的实现可能由多个类组成。
  所以如果想对NSArray进行Swizzing，必须获取到其“真身”进行Swizzing，直接对NSArray进行操作是无效的
    
  通过runtime函数取出本类
  NSArray                   __NSArrayI
  NSMutableArray            __NSArrayM
  NSDictionary              __NSDictionaryI
  NSMutableDictionary       __NSDictionaryM
 
 */

@implementation NSArray (MCError)

+ (void)load {
   
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method fromMethod = class_getInstanceMethod(objc_getClass("__NSArrayI"),@selector(objectAtIndex:));
        
        Method toMethod = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(mc_objectAtIndex:));
        
        method_exchangeImplementations(fromMethod, toMethod);
    });
   
}
 
- (void)mc_objectAtIndex:(NSUInteger)index{
    if (self.count - 1 < index) {
        
#ifdef DEBUG
        // 调试阶段
        return [self mc_objectAtIndex:index];
#else
        //发布阶段
        @try {
            return [self mc_objectAtIndex:index];
        } @catch (NSException *exception) {
            NSLog(@"数组crash",[exception callStackSymbols]);
            return nil;
        } @finally {
            
        }
#endif
    }else{
        return [self mc_objectAtIndex:index];
    }
}


@end
